import "./LoginView.scss";
import type { FormProps } from "antd";
import { Button, Checkbox, Form, Input, Image } from "antd";
import { FieldType } from "@/interface/ILoginView";
import { useEffect, useState } from "react";
import { getAuth, authcaptcha, login } from "@/business/UserRequest";
import { useDispatch } from "react-redux";
import { setUserInfo } from "@/stores/UserSlice";
import { useNavigate } from "react-router-dom";

const onFinishFailed: FormProps<FieldType>["onFinishFailed"] = (errorInfo) => {
  console.log("Failed:", errorInfo);
};
export default function LoginView() {
  const [authUrl, setAuthUrl] = useState("");
  const [captcha, setCaptcha] = useState("");
  const dispatch = useDispatch();
  const navigate = useNavigate();
  const onFinish: FormProps<FieldType>["onFinish"] = (values) => {
    // console.log("Success:", values.authCode);
    authcaptcha(values.authCode, captcha).then(
      (res: { code: number; data?: string; captcha?: string }) => {
        if (res.code === 0) {
          setAuthUrl(
            URL.createObjectURL(
              new Blob([res.data as string], { type: "image/svg+xml" })
            )
          );
          setCaptcha(res.captcha as string);
          return;
        }
        if (!values.remember) {
          return;
        }
        login({ username: values.username, password: values.password }).then(
          (res: any) => {
            dispatch(setUserInfo(res.data));
            navigate("/");
          }
        );
      }
    );
  };

  useEffect(() => {
    getAuth().then((res: { data: string; captcha: string }) => {
      setAuthUrl(
        URL.createObjectURL(new Blob([res.data], { type: "image/svg+xml" }))
      );
      setCaptcha(res.captcha);
    });
  }, []);
  
  return (
    <div className="login">
      <Form
        name="basic"
        labelCol={{ span: 8 }}
        wrapperCol={{ span: 16 }}
        style={{ maxWidth: 600 }}
        initialValues={{ remember: true }}
        onFinish={onFinish}
        onFinishFailed={onFinishFailed}
        autoComplete="off"
      >
        <Form.Item<FieldType>
          label="用户名"
          name="username"
          rules={[{ required: true, message: "请输入用户名!" }]}
        >
          <Input />
        </Form.Item>

        <Form.Item<FieldType>
          label="密码"
          name="password"
          rules={[{ required: true, message: "请输入密码!" }]}
        >
          <Input.Password autoComplete="true" />
        </Form.Item>
        <div style={{ display: "flex" }}>
          <Form.Item<FieldType>
            hasFeedback
            label="验证码"
            name="authCode"
            validateTrigger="onBlur"
            rules={[
              { required: true, message: "请输入验证码" },
              {
                pattern: new RegExp("^" + captcha + "$", "i"),
                message: "请输入准确的验证码",
              },
            ]}
          >
            <Input />
          </Form.Item>
          <Image width={100} height={40} src={authUrl} />
        </div>

        <Form.Item<FieldType>
          name="remember"
          valuePropName="checked"
          label={null}
        >
          <Checkbox>Remember me</Checkbox>
        </Form.Item>

        <Form.Item label={null}>
          <Button type="primary" htmlType="submit">
            Submit
          </Button>
        </Form.Item>
      </Form>
    </div>
  );
}




